// 加载动画处理
window.addEventListener('DOMContentLoaded', function() {
    const loadingScreen = document.getElementById('loading-screen');
    const mainContent = document.querySelector('.main-content');
    
    // 检查资源加载完成
    function checkResourcesLoaded() {
        if (document.readyState === 'complete') {
            // 淡出加载屏幕
            setTimeout(() => {
                loadingScreen.classList.add('fade-out');
                
                // 显示主内容
                setTimeout(() => {
                    mainContent.classList.add('fade-in');
                }, 300);
            }, 1000);
        } else {
            setTimeout(checkResourcesLoaded, 100);
        }
    }
    
    checkResourcesLoaded();
});

// 日程类
class Schedule {
    constructor(title, description, date, time, category, reminder, reminderTime = null) {
        this.id = Date.now().toString(); // 时间戳ID
        this.title = title;
        this.description = description;
        this.date = date;
        this.time = time;
        this.category = category;
        this.isCompleted = false;
        this.reminder = reminder;
        this.reminderTime = reminderTime; // 提前提醒分钟数
    }
}

// 全局确认对话框
function showConfirmDialog(title, message, confirmCallback, cancelCallback = null) {
    const dialog = document.getElementById('confirm-dialog');
    const titleElement = document.getElementById('confirm-title');
    const messageElement = document.getElementById('confirm-message');
    const cancelBtn = document.getElementById('confirm-cancel');
    const okBtn = document.getElementById('confirm-ok');
    
    // 设置内容
    titleElement.textContent = title;
    messageElement.textContent = message;
    
    // 显示对话框
    dialog.classList.remove('hidden');
    dialog.style.zIndex = '1000';
    
    // 确认处理
    const handleConfirm = () => {
        dialog.classList.add('hidden');
        confirmCallback();
        cleanup();
    };
    
    // 取消处理
    const handleCancel = () => {
        dialog.classList.add('hidden');
        cancelCallback?.();
        cleanup();
    };
    
    // 清理事件
    const cleanup = () => {
        okBtn.removeEventListener('click', handleConfirm);
        cancelBtn.removeEventListener('click', handleCancel);
        dialog.removeEventListener('click', handleDialogClick);
        document.removeEventListener('keydown', handleKeyDown);
    };
    
    // 点击外部关闭
    const handleDialogClick = (e) => {
        if (e.target === dialog) handleCancel();
    };
    
    // 键盘事件
    const handleKeyDown = (e) => {
        if (e.key === 'Escape') handleCancel();
        else if (e.key === 'Enter') handleConfirm();
    };
    
    // 绑定事件
    okBtn.addEventListener('click', handleConfirm);
    cancelBtn.addEventListener('click', handleCancel);
    dialog.addEventListener('click', handleDialogClick);
    document.addEventListener('keydown', handleKeyDown, { once: true });
}

// 全局变量
window.schedules = []; // 日程数据数组

// DOM元素获取
const addScheduleBtn = document.getElementById('add-schedule-btn');
const addScheduleModal = document.getElementById('add-schedule-modal');
const closeModalBtn = document.getElementById('close-modal-btn');
const cancelScheduleBtn = document.getElementById('cancel-schedule-btn');
const scheduleForm = document.getElementById('schedule-form');
const scheduleList = document.getElementById('schedule-list');
const welcomeMessage = document.getElementById('welcome-message');
const todayScheduleCount = document.getElementById('today-schedule-count');
const yesterdayDifference = document.getElementById('yesterday-difference');
const upcomingScheduleCount = document.getElementById('upcoming-schedule-count');
const completedScheduleCount = document.getElementById('completed-schedule-count');
const upcomingScheduleCard = document.getElementById('upcoming-schedule-card');
const upcomingScheduleModal = document.getElementById('upcoming-schedule-modal');
const closeUpcomingModalBtn = document.getElementById('close-upcoming-modal-btn');
const upcomingScheduleList = document.getElementById('upcoming-schedule-list');
// 今日日程相关DOM元素
const todayScheduleCard = document.getElementById('today-schedule-card');
const todayScheduleModal = document.getElementById('today-schedule-modal');
const closeTodayModalBtn = document.getElementById('close-today-modal-btn');
const todayScheduleList = document.getElementById('today-schedule-list');
const themeToggle = document.getElementById('theme-toggle');

// 获取日程数据
async function getSchedulesFromStorage() {
    try {
        // Electron环境
        if (window.electronAPI) {
            const result = await window.electronAPI.loadData();
            const schedules = result.success ? result.data : [];
            window.schedules = schedules;
            return schedules;
        } 
        // Web环境
        else {
            const schedulesStr = localStorage.getItem('schedules');
            const schedules = schedulesStr ? JSON.parse(schedulesStr) : [];
            window.schedules = schedules;
            return schedules;
        }
    } catch (error) {
        console.error('获取日程数据错误:', error);
        // 尝试从localStorage恢复
        try {
            const schedulesStr = localStorage.getItem('schedules');
            const schedules = schedulesStr ? JSON.parse(schedulesStr) : [];
            window.schedules = schedules;
            return schedules;
        } catch (fallbackError) {
            console.error('localStorage恢复失败:', fallbackError);
            window.schedules = [];
            return [];
        }
    }
}

// 保存日程数据
async function saveSchedulesToStorage(schedules) {
    // 参数验证
    if (!Array.isArray(schedules)) {
        console.error('保存日程数据失败: 参数必须是数组');
        return { success: false, error: '无效的日程数据格式' };
    }
    
    let isPrimaryStorageSuccess = false;
    
    try {
        // Electron环境
        if (window.electronAPI) {
            await window.electronAPI.saveData(schedules);
            isPrimaryStorageSuccess = true;
        }
        
        // 更新localStorage后备存储
        try {
            localStorage.setItem('schedules', JSON.stringify(schedules));
        } catch (localStorageError) {
            console.error('localStorage保存失败:', localStorageError);
        }
        
        // 更新导出数据
        updateUserDataExport(schedules);
        
        // 更新全局变量
        window.schedules = schedules;
        
        return { success: true };
    } catch (error) {
        console.error('保存日程数据错误:', error);
        // 尝试更新localStorage
        try {
            localStorage.setItem('schedules', JSON.stringify(schedules));
            window.schedules = schedules;
            return { success: true, warning: '主存储失败，已使用后备存储' };
        } catch (fallbackError) {
            console.error('所有存储方式失败:', fallbackError);
            return { success: false, error: '无法保存数据' };
        }
    }
}

// 更新导出数据
function updateUserDataExport(schedules) {
    const dataToExport = schedules || window.schedules || [];
    if (dataToExport.length === 0) return;
    
    const userData = {
        version: '1.0',
        exportDate: new Date().toISOString(),
        schedules: dataToExport
    };
    
    // 缓存导出数据
    localStorage.setItem('userDataForExport', JSON.stringify(userData));
}

// 导出用户数据
async function exportUserData() {
    try {
        // 准备导出数据
        let dataStr;
        
        // 尝试获取缓存数据
        try {
            const userDataStr = localStorage.getItem('userDataForExport');
            if (userDataStr) {
                const parsedData = JSON.parse(userDataStr);
                dataStr = JSON.stringify(parsedData, null, 2);
            }
        } catch (storageError) {
            console.warn('读取缓存数据失败，重新生成:', storageError);
        }
        
        // 生成新数据
        if (!dataStr) {
            try {
                const schedules = await getSchedulesFromStorage();
                const userData = {
                    version: '1.0',
                    exportDate: new Date().toISOString(),
                    schedules: schedules,
                    appVersion: process.env.APP_VERSION || 'unknown'
                };
                dataStr = JSON.stringify(userData, null, 2);
            } catch (scheduleError) {
                console.error('获取日程数据失败:', scheduleError);
                throw new Error('无法获取导出所需的数据');
            }
        }
        
        // 执行导出操作
        if (window.electronAPI) {
            // Electron环境原生导出
            const result = await window.electronAPI.exportData(dataStr);
            if (result.success) {
                showNotification('数据导出成功！', 'success');
                return { success: true };
            } else {
                const errorMessage = result.error || '未知错误';
                showNotification('导出失败：' + errorMessage, 'error');
                return { success: false, error: errorMessage };
            }
        } else {
            // Web环境浏览器下载
            if (typeof downloadFile === 'function') {
                downloadFile('user_data.json', dataStr, 'application/json');
                showNotification('数据已开始下载', 'success');
                return { success: true };
            } else {
                throw new Error('下载功能不可用');
            }
        }
    } catch (error) {
        console.error('导出数据过程发生错误:', error);
        showNotification('导出失败：' + error.message, 'error');
        return { success: false, error: error.message };
    }
}

// 下载文件辅助函数
function downloadFile(filename, content, contentType) {
    const blob = new Blob([content], { type: contentType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    setTimeout(() => {
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }, 100);
}

// 用户数据导入
async function importUserData() {
    try {
        // 首先显示确认对话框，提醒用户导入会覆盖原有数据
        await new Promise((resolve, reject) => {
            showConfirmDialog(
                '确认导入数据',
                '注意：导入数据将会覆盖当前所有日程数据，请确保已备份当前数据。是否继续导入？',
                () => resolve(),
                () => reject(new Error('用户取消导入'))
            );
        });
        
        // 数据导入处理函数
        async function processImportedData(importedData) {
            try {
                // 深度验证导入的数据结构
                if (!importedData || typeof importedData !== 'object') {
                    throw new Error('导入的数据不是有效的JSON对象');
                }
                
                // 检查是否有schedules属性且为数组
                if (!Array.isArray(importedData.schedules)) {
                    throw new Error('导入的数据格式错误：缺少有效的schedules数组');
                }
                
                // 验证schedules数组中的每个元素
                const validSchedules = importedData.schedules.filter(schedule => {
                    return schedule && typeof schedule === 'object';
                });
                
                if (validSchedules.length !== importedData.schedules.length) {
                    console.warn(`发现${importedData.schedules.length - validSchedules.length}个无效的日程项目，已自动过滤`);
                }
                
                if (validSchedules.length === 0) {
                    throw new Error('导入的数据中没有有效的日程项目');
                }
                
                // 保存过滤后的数据
                const saveResult = await saveSchedulesToStorage(validSchedules);
                if (!saveResult.success) {
                    throw new Error(saveResult.error || '保存数据失败');
                }
                
                // 更新应用数据 - 导入操作需要更新所有组件
                await refreshAppData({ stats: true, list: true, chart: true, calendar: true });
                
                return { success: true, importedCount: validSchedules.length };
            } catch (error) {
                console.error('处理导入数据时发生错误:', error);
                throw error;
            }
        }
        
        // Electron环境原生导入
        if (window.electronAPI) {
            const result = await window.electronAPI.importData();
            
            if (result.success && result.data) {
                try {
                    const processResult = await processImportedData(result.data);
                    showNotification(`数据导入成功！共导入${processResult.importedCount}个日程`, 'success');
                    return processResult;
                } catch (processError) {
                    showNotification('导入失败：' + processError.message, 'error');
                    return { success: false, error: processError.message };
                }
            } else if (result.cancelled) {
                // 用户取消了文件选择
                return { success: false, cancelled: true };
            } else {
                const errorMessage = result.error || '未知错误';
                showNotification('导入失败：' + errorMessage, 'error');
                return { success: false, error: errorMessage };
            }
        } else {
            // Web环境浏览器文件选择
            const fileInput = document.getElementById('file-import');
            
            if (!fileInput) {
                throw new Error('找不到文件导入组件');
            }
            
            // 创建一个Promise来处理文件选择
            return new Promise((resolve, reject) => {
                // 移除可能存在的旧事件监听器
                const newFileInput = fileInput.cloneNode(true);
                fileInput.parentNode.replaceChild(newFileInput, fileInput);
                
                newFileInput.onchange = async function(e) {
                    try {
                        const file = e.target.files[0];
                        if (!file) {
                            resolve({ success: false, cancelled: true });
                            return;
                        }
                        
                        // 检查文件类型
                        if (file.type && file.type !== 'application/json') {
                            throw new Error('请选择JSON格式的文件');
                        }
                        
                        // 限制文件大小
                        if (file.size > 10 * 1024 * 1024) { // 10MB限制
                            throw new Error('文件大小不能超过10MB');
                        }
                        
                        const userData = await new Promise((readResolve, readReject) => {
                            const reader = new FileReader();
                            
                            reader.onload = function(event) {
                                try {
                                    const parsedData = JSON.parse(event.target.result);
                                    readResolve(parsedData);
                                } catch (parseError) {
                                    readReject(new Error('解析JSON文件失败：' + parseError.message));
                                }
                            };
                            
                            reader.onerror = function() {
                                readReject(new Error('读取文件失败'));
                            };
                            
                            reader.readAsText(file);
                        });
                        
                        // 处理导入的数据
                        const processResult = await processImportedData(userData);
                        showNotification(`数据导入成功！共导入${processResult.importedCount}个日程`, 'success');
                        resolve(processResult);
                    } catch (error) {
                        showNotification('导入失败：' + error.message, 'error');
                        reject(error);
                    } finally {
                        // 重置文件输入
                        newFileInput.value = '';
                    }
                };
                
                // 触发文件选择对话框
                newFileInput.click();
            });
        }
    } catch (error) {
        console.error('导入数据过程发生错误:', error);
        showNotification('导入失败：' + error.message, 'error');
        return { success: false, error: error.message };
    }
}

// 获取今天日期字符串
function getTodayDateString() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 获取昨天日期字符串
function getYesterdayDateString() {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const year = yesterday.getFullYear();
    const month = String(yesterday.getMonth() + 1).padStart(2, '0');
    const day = String(yesterday.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 设置表单默认日期
function setFormDefaultDate() {
    const scheduleDate = document.getElementById('schedule-date');
    scheduleDate.value = getTodayDateString();
}

// 更新欢迎信息
function updateWelcomeMessage() {
    const today = new Date();
    const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    };
    const formattedDate = today.toLocaleDateString('zh-CN', options);
    welcomeMessage.textContent = `你好，今天是 ${formattedDate}`;
}

// 渲染日程列表
function renderScheduleList(schedules) {
    // 如果没有日程，显示空状态
    if (schedules.length === 0) {
        // 添加空状态过渡动画
        scheduleList.innerHTML = `
            <tr class="text-center schedule-item">
                <td colspan="5" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-calendar-o text-4xl mb-3 text-gray-300"></i>
                        <p>暂无日程</p>
                        <p class="text-sm mt-1">点击上方"添加日程"按钮创建你的日程</p>
                    </div>
                </td>
            </tr>
        `;
        // 激活动画
        setTimeout(() => {
            const emptyItem = scheduleList.querySelector('.schedule-item');
            if (emptyItem) emptyItem.classList.add('active');
        }, 10);
        return;
    }

    // 清空日程列表
    scheduleList.innerHTML = '';

    // 按日期和时间排序日程
    const sortedSchedules = [...schedules].sort((a, b) => {
        const dateA = new Date(`${a.date}T${a.time}`);
        const dateB = new Date(`${b.date}T${b.time}`);
        return dateA - dateB;
    });

    // 渲染每个日程项
    sortedSchedules.forEach((schedule, index) => {
        const scheduleDate = new Date(`${schedule.date}T${schedule.time}`);
        const isToday = schedule.date === getTodayDateString();
        const isOverdue = !schedule.isCompleted && scheduleDate < new Date() && !isToday;
        const isUpcoming = !schedule.isCompleted && isToday && scheduleDate > new Date();

        let statusClass = 'status-pending';
        let statusText = '待办';

        if (schedule.isCompleted) {
            statusClass = 'status-completed';
            statusText = '已完成';
        } else if (isOverdue) {
            statusClass = 'status-overdue';
            statusText = '已逾期';
        }

        let categoryClass = 'category-other';
        switch (schedule.category) {
            case '工作':
                categoryClass = 'category-work';
                break;
            case '学习':
                categoryClass = 'category-study';
                break;
            case '生活':
                categoryClass = 'category-life';
                break;
            case '健康':
                categoryClass = 'category-health';
                break;
        }

        const row = document.createElement('tr');
        row.className = `border-b border-gray-200 schedule-item schedule-item-hover ${isUpcoming ? 'reminder-pulse' : ''}`;
        row.dataset.id = schedule.id;
        row.innerHTML = `
            <td class="px-6 py-4">
                <div class="font-medium text-gray-800">${schedule.title.substring(0, 10) + (schedule.title.length > 10 ? '...' : '')}</div>
                ${schedule.description ? `<div class="text-sm text-gray-500 mt-1">${schedule.description.substring(0, 20) + (schedule.description.length > 20 ? '...' : '')}</div>` : ''}
            </td>
            <td class="px-6 py-4 text-gray-600">
                <div>${formatDate(schedule.date)}</div>
                <div class="text-sm text-gray-500">${schedule.time}</div>
            </td>
            <td class="px-6 py-4">
                <span class="category-tag ${categoryClass}">${schedule.category}</span>
            </td>
            <td class="px-6 py-4">
                <span class="status-badge ${statusClass}">${statusText}</span>
            </td>
            <td class="px-6 py-4 text-right">
                <div class="flex justify-end space-x-2">
                    <button class="text-gray-500 hover:text-primary transition-colors tooltip edit-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-pencil"></i>
                        <span class="tooltiptext">编辑</span>
                    </button>
                    ${schedule.isCompleted ? `
                    <button class="text-gray-500 hover:text-warning transition-colors tooltip undo-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-undo"></i>
                        <span class="tooltiptext">撤销</span>
                    </button>` : `
                    <button class="text-gray-500 hover:text-success transition-colors tooltip complete-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-check"></i>
                        <span class="tooltiptext">完成</span>
                    </button>`}
                    <button class="text-gray-500 hover:text-warning transition-colors tooltip delete-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-trash"></i>
                        <span class="tooltiptext">删除</span>
                    </button>
                </div>
            </td>
        `;
        scheduleList.appendChild(row);

        // 错开激活每个日程项的动画，创建级联效果
        setTimeout(() => {
            row.classList.add('active');
        }, 30 * index);
    });

    // 添加事件监听器到新创建的按钮
    addEventListenersToScheduleActions();
}

// 日期格式化为
function formatDate(dateString) {
    const date = new Date(dateString);
    const options = {
        month: '2-digit',
        day: '2-digit'
    };
    return date.toLocaleDateString('zh-CN', options);
}

// 添加日程操作事件监听
function addEventListenersToScheduleActions() {
    // 编辑按钮
    document.querySelectorAll('.edit-schedule-btn').forEach(btn => {
        btn.addEventListener('click', (e) => editSchedule(e.currentTarget.dataset.id));
    });

    // 完成按钮
    document.querySelectorAll('.complete-schedule-btn').forEach(btn => {
        btn.addEventListener('click', (e) => toggleCompleteSchedule(e.currentTarget.dataset.id, 'complete'));
    });
    
    // 撤销按钮
    document.querySelectorAll('.undo-schedule-btn').forEach(btn => {
        btn.addEventListener('click', (e) => toggleCompleteSchedule(e.currentTarget.dataset.id, 'undo'));
    });

    // 删除按钮
    document.querySelectorAll('.delete-schedule-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            showConfirmDialog('确认删除', '确定要删除这个日程吗？', () => {
                deleteSchedule(e.currentTarget.dataset.id);
            });
        });
    });
}

// 更新日程统计
function updateScheduleStats(schedules) {
    const today = getTodayDateString();
    const yesterday = getYesterdayDateString();
    const now = new Date();
    
    // 今日日程
    const allTodaySchedules = schedules.filter(schedule => schedule.date === today);
    window.todaySchedules = allTodaySchedules;
    
    // 今日已完成日程
    const completedTodaySchedules = allTodaySchedules.filter(schedule => schedule.isCompleted);
    
    // 显示今日日程数和已完成数
    todayScheduleCount.innerHTML = `${allTodaySchedules.length} <span class="text-sm">(已完成: ${completedTodaySchedules.length})</span>`;
    
    // 昨日日程比较
    const yesterdaySchedules = schedules.filter(schedule => schedule.date === yesterday);
    const yesterdayScheduleCount = yesterdaySchedules.length;
    const difference = allTodaySchedules.length - yesterdayScheduleCount;
    
    if (yesterdayDifference) {
        // 更新差异显示
        if (difference > 0) {
            yesterdayDifference.textContent = `+${difference}`;
            yesterdayDifference.className = 'text-success';
        } else if (difference < 0) {
            yesterdayDifference.textContent = `-${Math.abs(difference)}`;
            yesterdayDifference.className = 'text-danger';
        } else {
            yesterdayDifference.textContent = '0';
            yesterdayDifference.className = 'text-gray-800';
        }
    }
    
    console.log('较昨日比较:', {
        today: allTodaySchedules.length,
        yesterday: yesterdayScheduleCount,
        difference: difference
    });
    
    // 即将截止日程（24小时内）
    const next24Hours = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    const allUpcomingSchedules = schedules.filter(schedule => {
        const scheduleTime = new Date(`${schedule.date}T${schedule.time}`);
        return scheduleTime <= next24Hours && scheduleTime >= now;
    });
    
    // 即将截止已完成日程
    const completedUpcomingSchedules = allUpcomingSchedules.filter(schedule => schedule.isCompleted);
    
    // 显示即将截止日程数
    upcomingScheduleCount.innerHTML = `${allUpcomingSchedules.length} <span class="text-sm">(已完成: ${completedUpcomingSchedules.length})</span>`;
    window.upcomingSchedules = allUpcomingSchedules;
    
    // 计算已完成的日程数量
    const completedSchedules = schedules.filter(schedule => schedule.isCompleted);
    completedScheduleCount.textContent = completedSchedules.length;
    
    // 更新完成率
    const completionRateElement = document.getElementById('completion-rate');
    if (completionRateElement) {
        // 计算总日程数
        const totalSchedules = schedules.length;
        if (totalSchedules > 0) {
            // 完成率 = 已完成的日程数 / 总日程数
            const rate = Math.round((completedSchedules.length / totalSchedules) * 100);
            completionRateElement.textContent = `${rate}%`;
        } else {
            // 如果没有日程数据，显示0%
            completionRateElement.textContent = '0%';
        }
    }
    
    // 更新各个类别的日程数量
    const categoryCounts = {
        '工作': schedules.filter(schedule => schedule.category === '工作').length,
        '学习': schedules.filter(schedule => schedule.category === '学习').length,
        '生活': schedules.filter(schedule => schedule.category === '生活').length,
        '健康': schedules.filter(schedule => schedule.category === '健康').length,
        '其他': schedules.filter(schedule => schedule.category === '其他').length
    };
    
    // 更新DOM元素
    document.getElementById('category-count-work').textContent = `${categoryCounts['工作']} 个日程`;
    document.getElementById('category-count-study').textContent = `${categoryCounts['学习']} 个日程`;
    document.getElementById('category-count-life').textContent = `${categoryCounts['生活']} 个日程`;
    document.getElementById('category-count-health').textContent = `${categoryCounts['健康']} 个日程`;
    document.getElementById('category-count-other').textContent = `${categoryCounts['其他']} 个日程`;
    
    // 确保所有统计数据都是正确更新的
    console.log('更新后的统计数据:', {
        allSchedules: schedules.length,
        todaySchedules: allTodaySchedules.length,
        upcomingSchedules: upcomingSchedules.length,
        completedSchedules: completedSchedules.length,
        categoryCounts: categoryCounts
    });
}

// 全局图表实例
let scheduleChartInstance = null;
let completionRateChartInstance = null;

// 渲染统计图表
function renderChart(schedules) {
    const ctx = document.getElementById('schedule-chart').getContext('2d');
    
    // 按类别统计
    const categoryCount = {};
    schedules.forEach(schedule => {
        if (schedule.category) {
            categoryCount[schedule.category] = (categoryCount[schedule.category] || 0) + 1;
        }
    });
    
    // 颜色映射
    const colors = Object.keys(categoryCount).map(category => {
        const tailwindColors = {
            '工作': '#3b82f6',
            '学习': '#8b5cf6',
            '生活': '#EF4444',
            '健康': '#10b981',
            '其他': '#6b7280'
        };
        return tailwindColors[category] || '#6b7280';
    });
    
    // 销毁旧图表
    if (scheduleChartInstance !== null) {
        scheduleChartInstance.destroy();
    }
    
    // 创建图表
    scheduleChartInstance = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: Object.keys(categoryCount),
            datasets: [{
                data: Object.values(categoryCount),
                backgroundColor: colors,
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                },
                tooltip: {
                    animation: true,
                    animationDuration: 300,
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    titleColor: '#1f2937',
                    bodyColor: '#4b5563',
                    borderColor: 'rgba(79, 70, 229, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    displayColors: true,
                    cornerRadius: 8,
                    boxPadding: 4,
                    usePointStyle: true,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = schedules.length;
                            const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    },
                    filter: function() { return true; }
                }
            },
            cutout: '70%',
            hover: {
                mode: 'nearest',
                intersect: true,
                animationDuration: 200,
                backgroundColor: 'rgba(0, 0, 0, 0.05)',
                borderColor: '#4F46E5',
                borderWidth: 2
            },
            animation: {
                animateRotate: true,
                animateScale: true,
                duration: 800,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 渲染完成率图表
function renderCompletionRateChart(schedules) {
    const ctx = document.getElementById('completion-rate-chart').getContext('2d');
    
    // 统计状态数量
    const completedCount = schedules.filter(schedule => schedule.isCompleted).length;
    const pendingCount = schedules.filter(schedule => !schedule.isCompleted).length;
    
    // 销毁旧图表
    if (completionRateChartInstance !== null) {
        completionRateChartInstance.destroy();
    }
    
    // 创建图表
    completionRateChartInstance = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ['已完成', '未完成'],
            datasets: [{
                data: [completedCount, pendingCount],
                backgroundColor: ['#10B981', '#EF4444'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                },
                tooltip: {
                    // 增强的tooltip动画效果
                    animation: true,
                    animationDuration: 300,
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    titleColor: '#1f2937',
                    bodyColor: '#4b5563',
                    borderColor: 'rgba(79, 70, 229, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    displayColors: true,
                    cornerRadius: 8,
                    boxPadding: 4,
                    usePointStyle: true,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = schedules.length;
                            const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    },
                    // 添加悬浮时的交互效果
                    filter: function(tooltipItem, data) {
                        // 当鼠标悬停在图表上时，可以添加额外的高亮逻辑
                        return true;
                    }
                }
            },
            // 增强的鼠标悬浮效果
            hover: {
                mode: 'nearest',
                intersect: true,
                animationDuration: 200,
                backgroundColor: 'rgba(0, 0, 0, 0.05)',
                borderColor: '#4F46E5',
                borderWidth: 2
            },
            animation: {
                animateRotate: true,
                animateScale: true,
                duration: 800,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 处理日程添加和编辑
async function addSchedule(event) {
    event.preventDefault();
    
    const title = document.getElementById('schedule-title').value;
    const description = document.getElementById('schedule-description').value;
    const date = document.getElementById('schedule-date').value;
    const time = document.getElementById('schedule-time').value;
    const category = document.getElementById('schedule-category').value;
    const reminder = document.getElementById('schedule-reminder').checked;
    const reminderTime = document.getElementById('reminder-time').value;
    
    const schedules = await getSchedulesFromStorage();
    const mode = scheduleForm.dataset.mode || 'add';
    
    try {
        if (mode === 'edit') {
            const scheduleId = scheduleForm.dataset.scheduleId;
            if (!scheduleId) throw new Error('未找到要编辑的日程ID');
            
            const index = schedules.findIndex(s => s.id === scheduleId);
            if (index === -1) throw new Error('未找到指定的日程');
            
            // 更新日程
            schedules[index].title = title;
            schedules[index].description = description;
            schedules[index].date = date;
            schedules[index].time = time;
            schedules[index].category = category;
            schedules[index].reminder = reminder;
            schedules[index].reminderTime = reminder ? reminderTime : null;
            
            // 保存数据
            await saveSchedulesToStorage(schedules);
            
            // 设置提醒
            if (reminder) {
                setReminder(schedules[index]);
            }
            
            showNotification('日程更新成功！', 'success');
        } else {
            // 新增日程
            const newSchedule = new Schedule(title, description, date, time, category, reminder);
            newSchedule.reminderTime = reminder ? reminderTime : null;
            
            schedules.push(newSchedule);
            await saveSchedulesToStorage(schedules);
            
            // 设置提醒
            if (reminder) {
                setReminder(newSchedule);
            }
            
            showNotification('日程添加成功！', 'success');
        }
        
        // 关闭模态框并刷新界面
        closeModal();
        await refreshAppData({ stats: true, list: true, chart: true, calendar: true });
    } catch (error) {
        console.error('处理日程时出错:', error);
        showNotification(`操作失败: ${error.message}`, 'error');
    }
}

// 过滤状态
let filterState = {
    timeRange: 'all',
    status: 'all',
    searchTerm: ''
};

// 图表时间范围
let chartTimeRange = 'today';

// 分类弹窗过滤状态
let categoryFilterState = {
    category: '',
    timeRange: 'all',
    status: 'all',
    searchTerm: ''
};

// 分类弹窗相关DOM元素
const categoryScheduleModal = document.getElementById('category-schedule-modal');
const categoryModalTitle = document.getElementById('category-modal-title');
const categoryScheduleList = document.getElementById('category-schedule-list');
const categoryModalCloseBtn = document.getElementById('close-category-modal-btn');
const categorySearchInput = document.getElementById('category-search');
const categoryStatusButtons = {
    all: document.getElementById('category-status-all'),
    pending: document.getElementById('category-status-pending'),
    completed: document.getElementById('category-status-completed')
};
const categoryRangeButtons = {
    all: document.getElementById('category-range-all'),
    today: document.getElementById('category-range-today'),
    week: document.getElementById('category-range-week'),
    month: document.getElementById('category-range-month'),
    year: document.getElementById('category-range-year')
};


// 刷新应用数据
async function refreshAppData(components = { stats: true, list: true, chart: true, calendar: true }) {
    // 使用全局window.schedules变量，如果不存在则获取
    let allSchedules = window.schedules || [];
    if (allSchedules.length === 0) {
        allSchedules = await getSchedulesFromStorage();
    }
    
    // 用于统计的数据（保持原始数据）
    const schedulesForStats = [...allSchedules];
    
    // 用于图表的数据
    let schedulesForChart = [...allSchedules];
    
    // 用于列表显示的数据
    let schedulesForList = [...allSchedules];
    
    // 对图表数据应用时间范围过滤（使用chartTimeRange）
    if (chartTimeRange !== 'all') {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        switch(chartTimeRange) {
            case 'today':
                // 对图表数据应用时间过滤（今天）
                const todayStr = today.toISOString().split('T')[0];
                // 确保日期格式匹配，支持YYYY-MM-DD格式
                schedulesForChart = schedulesForChart.filter(schedule => {
                    // 尝试不同的日期匹配方式，确保能正确匹配
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === today.getFullYear() && 
                           scheduleDate.getMonth() === today.getMonth() && 
                           scheduleDate.getDate() === today.getDate();
                });
                break;
                
            case 'week':
                // 计算本周的开始（周一）和结束（周日）
                const dayOfWeek = today.getDay() || 7; // 0 -> 7（周日 -> 周一）
                const startOfWeek = new Date(today);
                startOfWeek.setDate(today.getDate() - dayOfWeek + 1);
                const endOfWeek = new Date(today);
                endOfWeek.setDate(today.getDate() + (7 - dayOfWeek));
                
                // 对图表数据应用时间过滤
                schedulesForChart = schedulesForChart.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate >= startOfWeek && scheduleDate <= endOfWeek;
                });
                break;
            
            case 'month':
                // 对图表数据应用时间过滤
                schedulesForChart = schedulesForChart.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear() && 
                           scheduleDate.getMonth() === now.getMonth();
                });
                break;
            
            case 'year':
                // 对图表数据应用时间过滤
                schedulesForChart = schedulesForChart.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear();
                });
                break;
        }
    }
    
    // 对列表数据应用时间范围过滤（使用filterState.timeRange）
    if (filterState.timeRange !== 'all') {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        switch(filterState.timeRange) {
            case 'today':
                // 对列表数据应用时间过滤（今天）
                schedulesForList = schedulesForList.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === today.getFullYear() && 
                           scheduleDate.getMonth() === today.getMonth() && 
                           scheduleDate.getDate() === today.getDate();
                });
                break;
                
            case 'week':
                // 计算本周的开始（周一）和结束（周日）
                const dayOfWeek = today.getDay() || 7; // 0 -> 7（周日 -> 周一）
                const startOfWeek = new Date(today);
                startOfWeek.setDate(today.getDate() - dayOfWeek + 1);
                const endOfWeek = new Date(today);
                endOfWeek.setDate(today.getDate() + (7 - dayOfWeek));
                
                // 对列表数据应用时间过滤
                schedulesForList = schedulesForList.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate >= startOfWeek && scheduleDate <= endOfWeek;
                });
                break;
            
            case 'month':
                // 对列表数据应用时间过滤
                schedulesForList = schedulesForList.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear() && 
                           scheduleDate.getMonth() === now.getMonth();
                });
                break;
            
            case 'year':
                // 对列表数据应用时间过滤
                schedulesForList = schedulesForList.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear();
                });
                break;
        }
    }
    
    // 应用状态过滤（仅对列表数据）
    if (filterState.status !== 'all') {
        if (filterState.status === 'pending') {
            schedulesForList = schedulesForList.filter(schedule => !schedule.isCompleted);
        } else if (filterState.status === 'completed') {
            schedulesForList = schedulesForList.filter(schedule => schedule.isCompleted);
        }
    }
    
    // 应用搜索过滤（仅对列表数据）
    if (filterState.searchTerm) {
        const searchLower = filterState.searchTerm.toLowerCase();
        schedulesForList = schedulesForList.filter(schedule => 
            schedule.title.toLowerCase().includes(searchLower) || 
            schedule.description.toLowerCase().includes(searchLower) ||
            schedule.category.toLowerCase().includes(searchLower)
        );
    }
    
    // 根据组件参数选择性渲染
    if (components.stats) updateScheduleStats(schedulesForStats);
    if (components.chart) {
        renderChart(schedulesForChart);
        renderCompletionRateChart(schedulesForChart);
    }
    if (components.list) renderScheduleList(schedulesForList);
    if (components.calendar) await renderCalendar();
}

// 编辑日程
function editSchedule(id) {
    // 在打开编辑窗口前关闭所有显示窗口
    closeTodayScheduleModal();
    closeUpcomingModal();
    closeCategoryScheduleModal();
    
    // 然后调用带参数的openModal函数
    openModal('edit', id);
}

// 切换日程完成状态
async function toggleCompleteSchedule(id, action = 'complete') {
    // 获取现有日程
    const schedules = await getSchedulesFromStorage();
    const index = schedules.findIndex(s => s.id === id);
    
    if (index !== -1) {
        // 保存更新前的日程信息，用于确定需要更新的日历日期
        const scheduleToUpdate = schedules[index];
        const targetDate = scheduleToUpdate.date;
        
        // 根据action参数设置完成状态，而不是简单切换
        if (action === 'complete' && !scheduleToUpdate.isCompleted) {
            // 只有未完成的任务才能被标记为完成
            schedules[index].isCompleted = true;
        } else if (action === 'undo' && scheduleToUpdate.isCompleted) {
            // 只有已完成的任务才能被撤销
            schedules[index].isCompleted = false;
        } else {
            // 如果操作无效（如对已完成任务点击完成，或对未完成任务点击撤销），直接返回
            return;
        }
        
        // 保存到存储
        await saveSchedulesToStorage(schedules);
        
        // 更新统计、列表和图表
        await refreshAppData({ stats: true, list: true, chart: true, calendar: false });
        
        // 局部更新日历中特定日期的单元格
        // 解析目标日期，检查是否在当前显示的月份内
        const targetDateObj = new Date(targetDate);
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth();
        
        // 只有当目标日期在当前显示的月份时，才进行局部更新
        if (targetDateObj.getFullYear() === currentYear && targetDateObj.getMonth() === currentMonth) {
            // 获取当天日期数字
            const dayOfMonth = targetDateObj.getDate();
            
            // 查找包含该日期的单元格
            const calendarCells = document.querySelectorAll('#calendar-body td');
            let targetCell = null;
            
            for (const cell of calendarCells) {
                const dateElement = cell.querySelector('div > div:first-child');
                if (dateElement && parseInt(dateElement.textContent) === dayOfMonth) {
                    // 确保这是当月的日期（不是上个月或下个月的）
                    if (!cell.classList.contains('bg-gray-50')) {
                        targetCell = cell;
                        break;
                    }
                }
            }
            
            if (targetCell) {
                // 获取单元格内容容器
                const cellContent = targetCell.querySelector('div');
                
                // 保留日期显示，移除现有的日程列表
                const dateElement = cellContent.querySelector('div:first-child');
                cellContent.innerHTML = '';
                cellContent.appendChild(dateElement);
                
                // 使用全局window.schedules变量
                const daySchedules = window.schedules.filter(schedule => schedule.date === targetDate);
                
                // 显示更新后的日程
                if (daySchedules.length > 0) {
                    const scheduleList = document.createElement('div');
                    scheduleList.classList.add('space-y-1', 'mt-1');
                    
                    // 显示全部日程
                    daySchedules.forEach(schedule => {
                        const scheduleItem = document.createElement('div');
                        scheduleItem.classList.add('text-xs', 'truncate', 'p-1', 'rounded', 'schedule-item-hover');
                        
                        // 根据分类设置颜色
                        let bgColor = '';
                        let textColor = 'text-white';
                        
                        switch(schedule.category) {
                            case '工作':
                                bgColor = 'bg-primary';
                                break;
                            case '学习':
                                bgColor = 'bg-secondary';
                                break;
                            case '生活':
                                bgColor = 'bg-red-500';
                                break;
                            case '健康':
                                bgColor = 'bg-success';
                                break;
                            default:
                                bgColor = 'bg-gray-400';
                        }
                        
                        scheduleItem.classList.add(bgColor, textColor);
                        
                        // 显示已完成状态
                        if (schedule.isCompleted) {
                            scheduleItem.innerHTML = `<i class="fa fa-check mr-1"></i>${schedule.title}`;
                        } else {
                            scheduleItem.textContent = schedule.title;
                        }
                        
                        // 添加点击事件，编辑日程
                        scheduleItem.addEventListener('click', () => {
                            editSchedule(schedule.id);
                        });
                        
                        scheduleList.appendChild(scheduleItem);
                    });
                    
                    cellContent.appendChild(scheduleList);
                }
            }
        }
    }
}

// 删除日程
async function deleteSchedule(id) {
    // 获取现有日程
    const schedules = await getSchedulesFromStorage();
    // 过滤掉要删除的日程
    const updatedSchedules = schedules.filter(schedule => schedule.id !== id);
    
    // 更新全局window.schedules变量
    window.schedules = updatedSchedules;
    
    // 保存到存储
    await saveSchedulesToStorage(updatedSchedules);
    
    // 更新UI - 删除操作需要更新所有组件
    await refreshAppData({ stats: true, list: true, chart: true, calendar: true });
    
    // 显示成功通知
    showNotification('日程已删除！', 'warning');
}

// 删除即将截止日程
function deleteUpcomingSchedule(id) {
    showConfirmDialog('确认删除', '确定要删除这个日程吗？', async () => {
        await deleteSchedule(id);
        // 重新打开模态框以刷新内容
        if (upcomingScheduleModal && upcomingScheduleModal.style.display === 'flex') {
            closeUpcomingModal();
            openUpcomingScheduleModal();
        }
    });
}

// 设置日程提醒
function setReminder(schedule) {
    const reminderTime = new Date(`${schedule.date}T${schedule.time}`);
    const now = new Date();
    const timeDiff = reminderTime.getTime() - now.getTime();
    
    // 只设置未来的提醒
    if (timeDiff > 0) {
        // 获取提醒时间（分钟），确保正确解析reminderTime值
        const reminderMinutes = schedule.reminderTime ? parseInt(schedule.reminderTime.toString()) : 5;
        // 计算提前提醒的毫秒数
        const reminderTimeout = timeDiff - reminderMinutes * 60 * 1000;
        
        if (reminderTimeout > 0) {
            setTimeout(() => {
                showNotification(`您有一个即将开始的日程：${schedule.title}`, 'warning');
                
                // 如果浏览器支持通知API，尝试显示桌面通知
                if ('Notification' in window && Notification.permission === 'granted') {
                    new Notification('日程提醒', {
                        body: `您有一个即将开始的日程：${schedule.title}\n时间：${formatDate(schedule.date)} ${schedule.time}`,
                        icon: ''
                    });
                } else if ('Notification' in window && Notification.permission !== 'denied') {
                    Notification.requestPermission();
                }
            }, reminderTimeout);
        }
    }
}

// 获取当前时间字符串
function getCurrentTimeString() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
}

// 打开模态框
async function openModal(mode = 'add', scheduleId = null, skipDateReset = false) {
    // 设置模态框标题
    const modalTitle = document.getElementById('modal-title');
    if (modalTitle) {
        modalTitle.textContent = mode === 'edit' ? '编辑日程' : '添加日程';
    }
    
    addScheduleModal.classList.remove('hidden');
    addScheduleModal.style.display = 'flex';
    // 阻止页面滚动
    document.body.style.overflow = 'hidden';
    // 聚焦到标题输入框
    document.getElementById('schedule-title').focus();
    
    // 如果是编辑模式，填充表单数据
    if (mode === 'edit' && scheduleId) {
        const schedules = await getSchedulesFromStorage();
        const schedule = schedules.find(s => s.id === scheduleId);
        if (schedule) {
            document.getElementById('schedule-title').value = schedule.title || '';
            document.getElementById('schedule-description').value = schedule.description || '';
            document.getElementById('schedule-date').value = schedule.date || '';
            document.getElementById('schedule-time').value = schedule.time || '';
            document.getElementById('schedule-category').value = schedule.category || '其他';
            document.getElementById('schedule-reminder').checked = !!schedule.reminder;
            
            // 设置提醒时间选择器
            const reminderTimeSelect = document.getElementById('reminder-time');
            if (reminderTimeSelect) {
                if (schedule.reminderTime) {
                    reminderTimeSelect.value = schedule.reminderTime;
                } else {
                    reminderTimeSelect.value = '5'; // 默认5分钟
                }
                reminderTimeSelect.disabled = !schedule.reminder;
            }
            
            // 存储当前编辑的日程ID在表单上
            scheduleForm.dataset.mode = 'edit';
            scheduleForm.dataset.scheduleId = scheduleId;
        }
    } else {
        // 设置表单模式和属性
        scheduleForm.dataset.mode = 'add';
        delete scheduleForm.dataset.scheduleId;
        
        if (skipDateReset) {
            // 只重置表单中的非日期字段，保留日期
            const scheduleDate = document.getElementById('schedule-date');
            const currentDateValue = scheduleDate.value;
            
            scheduleForm.reset();
            
            // 恢复日期值
            scheduleDate.value = currentDateValue;
        } else {
            // 完全重置表单
            scheduleForm.reset();
            // 设置默认日期为今天
            setFormDefaultDate();
        }
        // 设置默认时间为当前时间
        document.getElementById('schedule-time').value = getCurrentTimeString();
        // 禁用提醒时间选择器
        const reminderTimeSelect = document.getElementById('reminder-time');
        if (reminderTimeSelect) {
            reminderTimeSelect.disabled = true;
        }
    }
}

// 监听提醒复选框变化，控制提醒时间选择器的启用状态
document.addEventListener('DOMContentLoaded', function() {
    const reminderCheckbox = document.getElementById('schedule-reminder');
    const reminderTimeSelect = document.getElementById('reminder-time');
    
    if (reminderCheckbox && reminderTimeSelect) {
        // 初始状态
        reminderTimeSelect.disabled = !reminderCheckbox.checked;
        
        // 添加事件监听器
        reminderCheckbox.addEventListener('change', function() {
            reminderTimeSelect.disabled = !this.checked;
        });
    }

    // 编辑日程时，根据现有提醒状态设置选择器状态
    const scheduleForm = document.getElementById('schedule-form');
    if (scheduleForm) {
        // 不重写openModal函数，而是直接在openModal函数内部处理提醒时间设置
        // 这样可以避免函数重写导致的复杂性和潜在问题
        console.log('提醒时间功能已就绪');
    }
});
 
 // 关闭模态框
function closeModal() {
    addScheduleModal.style.display = 'none';
    addScheduleModal.classList.add('hidden');
    // 恢复页面滚动
    document.body.style.overflow = 'auto';
    // 重置表单和数据属性
    scheduleForm.reset();
    scheduleForm.dataset.mode = 'add';
    delete scheduleForm.dataset.scheduleId;
    setFormDefaultDate();
}

// 关闭今日日程模态框
function closeTodayScheduleModal() {
    if (todayScheduleModal) {
        todayScheduleModal.style.display = 'none';
        todayScheduleModal.classList.add('hidden');
        // 恢复页面滚动
        document.body.style.overflow = 'auto';
    }
}

// 关闭即将截止日程模态框
function closeUpcomingModal() {
    if (upcomingScheduleModal) {
        upcomingScheduleModal.style.display = 'none';
        upcomingScheduleModal.classList.add('hidden');
        // 恢复页面滚动
        document.body.style.overflow = 'auto';
    }
}

// 打开今日日程模态框并显示内容
function openTodayScheduleModal() {
    if (!todayScheduleModal || !todayScheduleList) return;
    
    // 清空列表
    todayScheduleList.innerHTML = '';
    
    // 获取今日日程
    const todaySchedules = window.todaySchedules || [];
    
    if (todaySchedules.length === 0) {
        // 如果没有今日日程，显示提示信息
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'text-center py-8 text-gray-500';
        emptyMessage.innerHTML = `
            <i class="fa fa-calendar-o text-xl mb-2"></i>
            <p>今日暂无日程</p>
            <p class="text-sm mt-1">点击添加日程按钮创建新的日程</p>
        `;
        todayScheduleList.appendChild(emptyMessage);
    } else {
        // 按时间排序日程
        const sortedSchedules = [...todaySchedules].sort((a, b) => {
            const dateA = new Date(`${a.date}T${a.time}`);
            const dateB = new Date(`${b.date}T${b.time}`);
            return dateA - dateB;
        });
        
        // 创建日程列表项
        sortedSchedules.forEach(schedule => {
            const scheduleItem = document.createElement('div');
            scheduleItem.className = `p-4 border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors ${schedule.isCompleted ? 'bg-gray-50 opacity-75' : ''}`;
            
            // 设置分类样式
            let categoryBgClass = 'bg-gray-100';
            let categoryTextClass = 'text-gray-600';
            
            switch (schedule.category) {
                case '工作':
                    categoryBgClass = 'bg-blue-100';
                    categoryTextClass = 'text-blue-600';
                    break;
                case '学习':
                    categoryBgClass = 'bg-purple-100';
                    categoryTextClass = 'text-purple-600';
                    break;
                case '生活':
                    categoryBgClass = 'bg-red-100';
                    categoryTextClass = 'text-red-600';
                    break;
                case '健康':
                    categoryBgClass = 'bg-green-100';
                    categoryTextClass = 'text-green-600';
                    break;
            }
            
            // 填充内容
            scheduleItem.innerHTML = `
                <div class="flex flex-col md:flex-row md:items-start justify-between">
                    <div class="flex-1 mb-3 md:mb-0 md:mr-4">
                        <h4 class="font-medium text-gray-800 mb-1 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.title}</h4>
                        <div class="flex flex-wrap gap-2 text-sm mb-2">
                            <span class="px-2 py-1 rounded-full ${categoryBgClass} ${categoryTextClass}">${schedule.category}</span>
                            <span class="px-2 py-1 rounded-full bg-gray-100 text-gray-600">${schedule.time}</span>
                            ${schedule.isCompleted ? '<span class="px-2 py-1 rounded-full bg-green-100 text-green-600">已完成</span>' : ''}
                        </div>
                        ${schedule.description ? `<p class="text-sm text-gray-600 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.description}</p>` : ''}
                    </div>
                    <div class="flex space-x-2">
                        <button class="edit-today-schedule-btn text-gray-500 hover:text-primary transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-pencil"></i>
                            <span class="tooltiptext">编辑</span>
                        </button>
                        ${!schedule.isCompleted ? `
                        <button class="complete-today-schedule-btn text-gray-500 hover:text-success transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-check"></i>
                            <span class="tooltiptext">完成</span>
                        </button>
                        ` : ''}
                        <button class="delete-today-schedule-btn text-gray-500 hover:text-warning transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-trash"></i>
                            <span class="tooltiptext">删除</span>
                        </button>
                    </div>
                </div>
            `;
            
            todayScheduleList.appendChild(scheduleItem);
        });
        
        // 添加事件监听器
        document.querySelectorAll('.edit-today-schedule-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;
                closeTodayScheduleModal();
                editSchedule(id);
            });
        });
        
        document.querySelectorAll('.complete-today-schedule-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;

                
                showConfirmDialog('确认完成', '确定要将此日程标记为已完成吗？', async () => {
                    await toggleCompleteSchedule(id);
                    openTodayScheduleModal(); // 重新打开模态框以刷新内容
                });
            });
        });
        
        document.querySelectorAll('.delete-today-schedule-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;
                // 显示确认对话框

                
                showConfirmDialog('确认删除', '确定要删除这个日程吗？', async () => {
                    await deleteSchedule(id);
                    openTodayScheduleModal(); // 重新打开模态框以刷新内容
                });
            });
        });
    }
    
    // 显示模态框
    todayScheduleModal.classList.remove('hidden');
    todayScheduleModal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 打开即将截止日程模态框并显示内容
function openUpcomingScheduleModal() {
    if (!upcomingScheduleModal || !upcomingScheduleList) return;
    
    // 清空列表
    upcomingScheduleList.innerHTML = '';
    
    // 获取即将截止的日程
    const upcomingSchedules = window.upcomingSchedules || [];
    
    if (upcomingSchedules.length === 0) {
        // 如果没有即将截止的日程，显示提示信息
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'text-center py-8 text-gray-500';
        emptyMessage.innerHTML = `
            <i class="fa fa-check-circle text-xl mb-2"></i>
            <p>没有即将截止的日程</p>
        `;
        upcomingScheduleList.appendChild(emptyMessage);
    } else {
        // 按时间排序日程
        const sortedSchedules = [...upcomingSchedules].sort((a, b) => {
            const dateA = new Date(`${a.date}T${a.time}`);
            const dateB = new Date(`${b.date}T${b.time}`);
            return dateA - dateB;
        });
        
        // 创建日程列表项
        sortedSchedules.forEach(schedule => {
            const scheduleItem = document.createElement('div');
            scheduleItem.className = 'p-4 border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors';
            
            // 计算剩余时间
            const now = new Date();
            const scheduleTime = new Date(`${schedule.date}T${schedule.time}`);
            const timeDiff = scheduleTime - now;
            
            let timeRemainingText = '';
            let timeClass = '';
            
            if (timeDiff > 0) {
                const hours = Math.floor(timeDiff / (1000 * 60 * 60));
                const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
                
                if (hours > 0) {
                    timeRemainingText = `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}后`;
                } else {
                    timeRemainingText = `${minutes}分钟后`;
                }
                
                // 根据剩余时间设置颜色
                if (hours < 1) {
                    timeClass = 'text-danger';
                } else if (hours < 3) {
                    timeClass = 'text-accent';
                } else {
                    timeClass = 'text-success';
                }
            } else {
                timeRemainingText = '现在';
                timeClass = 'text-danger';
            }
            
            // 设置分类样式
            let categoryBgClass = 'bg-gray-100';
            let categoryTextClass = 'text-gray-600';
            
            switch (schedule.category) {
                case '工作':
                    categoryBgClass = 'bg-blue-100';
                    categoryTextClass = 'text-blue-600';
                    break;
                case '学习':
                    categoryBgClass = 'bg-purple-100';
                    categoryTextClass = 'text-purple-600';
                    break;
                case '生活':
                    categoryBgClass = 'bg-red-100';
                    categoryTextClass = 'text-red-600';
                    break;
                case '健康':
                    categoryBgClass = 'bg-green-100';
                    categoryTextClass = 'text-green-600';
                    break;
            }
            
            // 填充内容
            scheduleItem.innerHTML = `
                <div class="flex flex-col md:flex-row md:items-start justify-between">
                    <div class="flex-1 mb-3 md:mb-0 md:mr-4">
                        <h4 class="font-medium text-gray-800 mb-1 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.title}</h4>
                        <div class="flex flex-wrap gap-2 text-sm mb-2">
                            <span class="px-2 py-1 rounded-full ${categoryBgClass} ${categoryTextClass}">${schedule.category}</span>
                            <span class="px-2 py-1 rounded-full bg-gray-100 text-gray-600">${schedule.date} ${schedule.time}</span>
                            <span class="px-2 py-1 rounded-full bg-gray-100 ${timeClass}">${timeRemainingText}</span>
                            ${schedule.isCompleted ? '<span class="px-2 py-1 rounded-full bg-green-100 text-green-600">已完成</span>' : ''}
                        </div>
                        ${schedule.description ? `<p class="text-sm text-gray-600 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.description}</p>` : ''}
                    </div>
                    <div class="flex space-x-2">
                        <button class="edit-upcoming-schedule-btn text-gray-500 hover:text-primary transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-pencil"></i>
                            <span class="tooltiptext">编辑</span>
                        </button>
                        ${!schedule.isCompleted ? `
                        <button class="complete-upcoming-schedule-btn text-gray-500 hover:text-success transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-check"></i>
                            <span class="tooltiptext">完成</span>
                        </button>
                        ` : ''}
                        <button class="delete-upcoming-schedule-btn text-gray-500 hover:text-warning transition-colors tooltip" data-id="${schedule.id}">
                            <i class="fa fa-trash"></i>
                            <span class="tooltiptext">删除</span>
                        </button>
                    </div>
                </div>
            `;
            

            
            upcomingScheduleList.appendChild(scheduleItem);
        });
        

        
        // 添加编辑按钮事件监听器
        document.querySelectorAll('.edit-upcoming-schedule-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;
                editSchedule(id);
            });
        });
        
        // 添加完成按钮事件监听器
        document.querySelectorAll('.complete-upcoming-schedule-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;
                
                showConfirmDialog('确认完成', '确定要将此日程标记为已完成吗？', async () => {
                    await toggleCompleteSchedule(id);
                    openUpcomingScheduleModal(); // 重新打开模态框以刷新内容
                });
            });
        });
        
        // 添加删除按钮事件监听器
        document.querySelectorAll('.delete-upcoming-schedule-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const id = e.currentTarget.dataset.id;
                
                showConfirmDialog('确认删除', '确定要删除这个日程吗？', async () => {
                    await deleteUpcomingSchedule(id);
                    openUpcomingScheduleModal(); // 重新打开模态框以刷新内容
                });
            });
        });
      }
    
    // 显示模态框
    upcomingScheduleModal.classList.remove('hidden');
    upcomingScheduleModal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="flex items-center space-x-2">
            <i class="fa ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-exclamation-triangle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除通知
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        notification.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 更新统计按钮样式
function updateStatsButtons(activeId) {
    const buttons = ['stats-today', 'stats-this-week', 'stats-this-month', 'stats-this-year'];
    
    buttons.forEach(id => {
        const button = document.getElementById(id);
        if (button) {
            if (id === activeId) {
                button.classList.add('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.remove('text-gray-500');
            } else {
                button.classList.remove('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.add('text-gray-500');
            }
        }
    });
}

// 更新过滤按钮样式
function updateFilterButtons(activeId) {
    const buttons = ['filter-all', 'filter-pending', 'filter-completed'];
    
    buttons.forEach(id => {
        const button = document.getElementById(id);
        if (button) {
            if (id === activeId) {
                button.classList.add('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.remove('text-gray-500');
            } else {
                button.classList.remove('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.add('text-gray-500');
            }
        }
    });
}

// 更新时间范围按钮样式
function updateRangeButtons(activeId) {
    const buttons = ['range-all', 'range-week', 'range-month', 'range-year'];
    
    buttons.forEach(id => {
        const button = document.getElementById(id);
        if (button) {
            if (id === activeId) {
                button.classList.add('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.remove('text-gray-500');
            } else {
                button.classList.remove('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.add('text-gray-500');
            }
        }
    });
}

// 更新分类弹窗状态按钮样式
function updateCategoryStatusButtons(activeStatus) {
    Object.keys(categoryStatusButtons).forEach(status => {
        const button = categoryStatusButtons[status];
        if (button) {
            if (status === activeStatus) {
                button.classList.add('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.remove('text-gray-500');
            } else {
                button.classList.remove('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.add('text-gray-500');
            }
        }
    });
}

// 更新分类弹窗时间范围按钮样式
function updateCategoryRangeButtons(activeRange) {
    Object.keys(categoryRangeButtons).forEach(range => {
        const button = categoryRangeButtons[range];
        if (button) {
            if (range === activeRange) {
                button.classList.add('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.remove('text-gray-500');
            } else {
                button.classList.remove('text-primary', 'font-medium', 'bg-primary/10');
                button.classList.add('text-gray-500');
            }
        }
    });
}

// 打开分类日程弹窗
async function openCategoryScheduleModal(category) {
    // 设置当前分类
    categoryFilterState.category = category;
    categoryModalTitle.textContent = `${category} 日程`;
    
    // 重置搜索框
    categorySearchInput.value = '';
    categoryFilterState.searchTerm = '';
    
    // 设置时间范围为全部并更新按钮样式
    categoryFilterState.timeRange = 'all';
    updateCategoryRangeButtons('all');
    
    // 显示弹窗
    if (categoryScheduleModal) {
        categoryScheduleModal.classList.remove('hidden');
        categoryScheduleModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }
    
    // 渲染分类日程列表
    await renderCategorySchedules();
}

// 关闭分类日程弹窗
function closeCategoryScheduleModal() {
    if (categoryScheduleModal) {
        categoryScheduleModal.classList.add('hidden');
        document.body.style.overflow = '';
    }
}

// 渲染分类日程列表
async function renderCategorySchedules() {
    // 获取所有日程数据
    const allSchedules = await getSchedulesFromStorage();
    
    // 先按分类过滤
    let filteredSchedules = allSchedules.filter(schedule => 
        schedule.category === categoryFilterState.category
    );
    
    // 应用时间范围过滤
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    
    if (categoryFilterState.timeRange !== 'all') {
        switch(categoryFilterState.timeRange) {
            case 'today':
                filteredSchedules = filteredSchedules.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === today.getFullYear() && 
                           scheduleDate.getMonth() === today.getMonth() && 
                           scheduleDate.getDate() === today.getDate();
                });
                break;
            case 'week':
                const dayOfWeek = today.getDay() || 7;
                const startOfWeek = new Date(today);
                startOfWeek.setDate(today.getDate() - dayOfWeek + 1);
                const endOfWeek = new Date(today);
                endOfWeek.setDate(today.getDate() + (7 - dayOfWeek));
                
                filteredSchedules = filteredSchedules.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate >= startOfWeek && scheduleDate <= endOfWeek;
                });
                break;
            case 'month':
                filteredSchedules = filteredSchedules.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear() && 
                           scheduleDate.getMonth() === now.getMonth();
                });
                break;
            case 'year':
                filteredSchedules = filteredSchedules.filter(schedule => {
                    const scheduleDate = new Date(schedule.date);
                    return scheduleDate.getFullYear() === now.getFullYear();
                });
                break;
        }
    }
    
    // 应用状态过滤
    if (categoryFilterState.status !== 'all') {
        if (categoryFilterState.status === 'pending') {
            filteredSchedules = filteredSchedules.filter(schedule => !schedule.isCompleted);
        } else if (categoryFilterState.status === 'completed') {
            filteredSchedules = filteredSchedules.filter(schedule => schedule.isCompleted);
        }
    }
    
    // 应用搜索过滤
    if (categoryFilterState.searchTerm) {
        const searchLower = categoryFilterState.searchTerm.toLowerCase();
        filteredSchedules = filteredSchedules.filter(schedule => 
            schedule.title.toLowerCase().includes(searchLower) || 
            schedule.description.toLowerCase().includes(searchLower) ||
            schedule.category.toLowerCase().includes(searchLower)
        );
    }
    
    // 按日期和时间排序
    filteredSchedules.sort((a, b) => {
        const dateA = new Date(`${a.date}T${a.time}`);
        const dateB = new Date(`${b.date}T${b.time}`);
        return dateA - dateB;
    });
    
    // 清空列表
    if (categoryScheduleList) {
        categoryScheduleList.innerHTML = '';
        
        if (filteredSchedules.length === 0) {
            // 显示空状态
            categoryScheduleList.innerHTML = `
                <div class="text-center py-12 text-gray-500 schedule-item">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-calendar-o text-4xl mb-3 text-gray-300"></i>
                        <p>该分类下暂无符合条件的日程</p>
                    </div>
                </div>
            `;
            // 激活动画
            setTimeout(() => {
                const emptyItem = categoryScheduleList.querySelector('.schedule-item');
                if (emptyItem) emptyItem.classList.add('active');
            }, 10);
        } else {
            // 渲染日程项
            filteredSchedules.forEach((schedule, index) => {
                const scheduleItem = document.createElement('div');
                scheduleItem.className = 'p-4 border-b border-gray-100 schedule-item hover:bg-gray-50 transition-colors';
                scheduleItem.dataset.id = schedule.id;
                
                // 获取分类的样式类
                let categoryBgClass = 'bg-gray-100';
                let categoryTextClass = 'text-gray-600';
                
                switch(schedule.category) {
                    case '工作':
                        categoryBgClass = 'bg-blue-100';
                        categoryTextClass = 'text-blue-600';
                        break;
                    case '学习':
                        categoryBgClass = 'bg-purple-100';
                        categoryTextClass = 'text-purple-600';
                        break;
                    case '生活':
                    categoryBgClass = 'bg-red-100';
                    categoryTextClass = 'text-red-600';
                    break;
                    case '健康':
                        categoryBgClass = 'bg-green-100';
                        categoryTextClass = 'text-green-600';
                        break;
                    case '其他':
                        categoryBgClass = 'bg-gray-100';
                        categoryTextClass = 'text-gray-600';
                        break;
                }
                
                // 计算剩余时间文本
                const now = new Date();
                const scheduleDateTime = new Date(`${schedule.date}T${schedule.time}`);
                const timeDiff = scheduleDateTime - now;
                let timeClass = '';
                let timeRemainingText = '';
                
                if (timeDiff < 0 && !schedule.isCompleted) {
                    timeClass = 'text-danger';
                    timeRemainingText = '已过期';
                } else if (timeDiff < 24 * 60 * 60 * 1000 && !schedule.isCompleted) {
                    timeClass = 'text-orange-500';
                    timeRemainingText = '即将到期';
                } else {
                    timeClass = 'text-gray-600';
                    timeRemainingText = schedule.date;
                }
                
                // 填充内容
                scheduleItem.innerHTML = `
                    <div class="flex flex-col md:flex-row md:items-start justify-between">
                        <div class="flex-1 mb-3 md:mb-0 md:mr-4">
                            <h4 class="font-medium text-gray-800 mb-1 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.title}</h4>
                            <div class="flex flex-wrap gap-2 text-sm mb-2">
                                <span class="px-2 py-1 rounded-full ${categoryBgClass} ${categoryTextClass}">${schedule.category}</span>
                                <span class="px-2 py-1 rounded-full bg-gray-100 text-gray-600">${schedule.date} ${schedule.time}</span>
                                <span class="px-2 py-1 rounded-full bg-gray-100 ${timeClass}">${timeRemainingText}</span>
                                ${schedule.isCompleted ? '<span class="px-2 py-1 rounded-full bg-green-100 text-green-600">已完成</span>' : ''}
                            </div>
                            ${schedule.description ? `<p class="text-sm text-gray-600 ${schedule.isCompleted ? 'line-through text-gray-500' : ''}">${schedule.description}</p>` : ''}
                        </div>
                        <div class="flex space-x-2">
                            <button class="edit-category-schedule-btn text-gray-500 hover:text-primary transition-colors tooltip" data-id="${schedule.id}">
                                <i class="fa fa-pencil"></i>
                                <span class="tooltiptext">编辑</span>
                            </button>
                            ${!schedule.isCompleted ? `
                            <button class="complete-category-schedule-btn text-gray-500 hover:text-success transition-colors tooltip" data-id="${schedule.id}">
                                <i class="fa fa-check"></i>
                                <span class="tooltiptext">完成</span>
                            </button>
                            ` : ''}
                            <button class="delete-category-schedule-btn text-gray-500 hover:text-warning transition-colors tooltip" data-id="${schedule.id}">
                                <i class="fa fa-trash"></i>
                                <span class="tooltiptext">删除</span>
                            </button>
                        </div>
                    </div>
                `;
                

                
                categoryScheduleList.appendChild(scheduleItem);
                
                // 错开激活每个日程项的动画，创建级联效果
                setTimeout(() => {
                    scheduleItem.classList.add('active');
                }, 30 * index);
            });
            
            // 添加编辑按钮事件监听器
            document.querySelectorAll('.edit-category-schedule-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const id = e.currentTarget.dataset.id;
                    editSchedule(id);
                });
            });
            
            // 添加完成按钮事件监听器
            document.querySelectorAll('.complete-category-schedule-btn').forEach(btn => {
                btn.addEventListener('click', async (e) => {
                    e.stopPropagation();
                    const id = e.currentTarget.dataset.id;
                    
                    showConfirmDialog('确认完成', '确定要将此日程标记为已完成吗？', async () => {
                        await toggleCompleteSchedule(id);
                        await renderCategorySchedules(); // 重新渲染分类列表
                    });
                });
            });
            
            // 添加删除按钮事件监听器
            document.querySelectorAll('.delete-category-schedule-btn').forEach(btn => {
                btn.addEventListener('click', async (e) => {
                    e.stopPropagation();
                    const id = e.currentTarget.dataset.id;
                    
                    showConfirmDialog('确认删除', '确定要删除这个日程吗？', async () => {
                        await deleteSchedule(id);
                        await renderCategorySchedules(); // 重新渲染分类列表
                    });
                });
            });
        }
    }
}



// 初始化应用
async function initApp() {
    setFormDefaultDate();
    updateWelcomeMessage();
    
    // 默认加载全部数据
    await refreshAppData({ stats: true, list: true, chart: true, calendar: true });
    
    // 统计图表默认选中本日
    updateStatsButtons('stats-today');
    chartTimeRange = 'today';
    await refreshAppData({ stats: true, list: false, chart: true, calendar: false });
    
    // 列表过滤默认全部
    filterState.timeRange = 'all';
    updateRangeButtons('range-all');
    await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
    
    // 请求通知权限
    if ('Notification' in window && Notification.permission !== 'granted' && Notification.permission !== 'denied') {
        Notification.requestPermission();
    }
}

// 添加事件监听器
function addEventListeners() {
    // 添加日程按钮点击事件
    addScheduleBtn.addEventListener('click', function() {
        scheduleForm.reset();
        setFormDefaultDate();
        document.getElementById('schedule-title').focus();
        openModal();
    });
    
    // 关闭模态框按钮点击事件
    closeModalBtn.addEventListener('click', closeModal);
    cancelScheduleBtn.addEventListener('click', closeModal);
    
    // 点击模态框外部关闭模态框
    addScheduleModal.addEventListener('click', (e) => {
        if (e.target === addScheduleModal) {
            closeModal();
        }
    });
    
    // 今日日程模态框相关事件
    if (todayScheduleModal) {
        // 点击外部关闭
        todayScheduleModal.addEventListener('click', (e) => {
            if (e.target === todayScheduleModal) {
                closeTodayScheduleModal();
            }
        });
        
        // 关闭按钮点击事件
        if (closeTodayModalBtn) {
            closeTodayModalBtn.addEventListener('click', closeTodayScheduleModal);
        }
    }
    
    // 点击今日日程卡片打开模态框
    if (todayScheduleCard) {
        todayScheduleCard.addEventListener('click', openTodayScheduleModal);
    }
    
    // 即将截止模态框点击外部关闭
    if (upcomingScheduleModal) {
        upcomingScheduleModal.addEventListener('click', (e) => {
            if (e.target === upcomingScheduleModal) {
                closeUpcomingModal();
            }
        });
    }
    
    // 表单提交事件
    scheduleForm.addEventListener('submit', addSchedule);
    
    // 点击即将截止卡片打开模态框
    if (upcomingScheduleCard) {
        upcomingScheduleCard.addEventListener('click', openUpcomingScheduleModal);
    }
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            if (addScheduleModal.style.display === 'flex') {
                closeModal();
            } else if (todayScheduleModal && todayScheduleModal.style.display === 'flex') {
                closeTodayScheduleModal();
            } else if (upcomingScheduleModal && upcomingScheduleModal.style.display === 'flex') {
                closeUpcomingModal();
            }
        }
    });
    
    // 关闭即将截止模态框按钮
    if (closeUpcomingModalBtn) {
        closeUpcomingModalBtn.addEventListener('click', closeUpcomingModal);
    }
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            if (addScheduleModal.style.display === 'flex') {
                closeModal();
            } else if (upcomingScheduleModal && upcomingScheduleModal.style.display === 'flex') {
                closeUpcomingModal();
            }
        }
    });
    
    // 统计图表时间范围选择
    document.getElementById('stats-today').addEventListener('click', async function() {
        updateStatsButtons('stats-today');
        chartTimeRange = 'today';
        await refreshAppData({ stats: true, list: false, chart: true, calendar: false });
    });
    
    document.getElementById('stats-this-week').addEventListener('click', async function() {
        updateStatsButtons('stats-this-week');
        chartTimeRange = 'week';
        await refreshAppData({ stats: true, list: false, chart: true, calendar: false });
    });
    
    document.getElementById('stats-this-month').addEventListener('click', async function() {
        updateStatsButtons('stats-this-month');
        chartTimeRange = 'month';
        await refreshAppData({ stats: true, list: false, chart: true, calendar: false });
    });
    
    document.getElementById('stats-this-year').addEventListener('click', async function() {
        updateStatsButtons('stats-this-year');
        chartTimeRange = 'year';
        await refreshAppData({ stats: true, list: false, chart: true, calendar: false });
    });
    
    // 管理分类按钮已移除
    
    // 过滤动画辅助函数
    async function applyFilterWithAnimation(updaterFunction) {
        // 回到列表顶部
        if (scheduleList) {
            scheduleList.scrollTo({ top: 0, behavior: 'smooth' });
        }
        
        // 添加退出动画
        const existingItems = scheduleList.querySelectorAll('.schedule-item');
        existingItems.forEach(item => {
            item.classList.add('schedule-item-exit');
        });
        
        // 延迟后应用过滤
        setTimeout(async () => {
            await updaterFunction();
            
            // 添加进入动画
            setTimeout(() => {
                const newItems = scheduleList.querySelectorAll('.schedule-item:not(.schedule-item-exit)');
                newItems.forEach((item, index) => {
                    item.classList.add('schedule-item-enter');
                    // 错开动画时间
                    setTimeout(() => item.classList.add('appear'), index * 30);
                });
            }, 50);
        }, 150);
    }
    
    document.getElementById('filter-all').addEventListener('click', async function() {
        updateFilterButtons('filter-all');
        filterState.status = 'all';
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    document.getElementById('filter-pending').addEventListener('click', async function() {
        updateFilterButtons('filter-pending');
        filterState.status = 'pending';
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    document.getElementById('filter-completed').addEventListener('click', async function() {
        updateFilterButtons('filter-completed');
        filterState.status = 'completed';
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    // 时间范围过滤按钮事件监听
    document.getElementById('range-all')?.addEventListener('click', async function() {
        updateRangeButtons('range-all');
        filterState.timeRange = 'all';
        // 应用过滤并添加动画效果
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    document.getElementById('range-week')?.addEventListener('click', async function() {
        updateRangeButtons('range-week');
        filterState.timeRange = 'week';
        // 应用过滤并添加动画效果
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    document.getElementById('range-month')?.addEventListener('click', async function() {
        updateRangeButtons('range-month');
        filterState.timeRange = 'month';
        // 应用过滤并添加动画效果
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    document.getElementById('range-year')?.addEventListener('click', async function() {
        updateRangeButtons('range-year');
        filterState.timeRange = 'year';
        // 应用过滤并添加动画效果
        await applyFilterWithAnimation(async () => {
            await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
        });
    });
    
    // 搜索框事件监听（带防抖）
    let mainSearchTimeout;
    document.getElementById('schedule-search')?.addEventListener('input', async function(e) {
        clearTimeout(mainSearchTimeout);
        filterState.searchTerm = e.target.value.trim();
        
        mainSearchTimeout = setTimeout(async () => {
            // 回到列表顶部
            if (scheduleList) {
                scheduleList.scrollTo({ top: 0, behavior: 'smooth' });
            }
            
            // 添加退出动画
            const existingItems = scheduleList.querySelectorAll('.schedule-item');
            existingItems.forEach(item => item.classList.add('schedule-item-exit'));
            
            // 延迟后重新渲染
            setTimeout(async () => {
                await refreshAppData({ stats: false, list: true, chart: false, calendar: false });
                
                // 添加进入动画
                setTimeout(() => {
                    const newItems = scheduleList.querySelectorAll('.schedule-item:not(.schedule-item-exit)');
                    newItems.forEach((item, index) => {
                        item.classList.add('schedule-item-enter');
                        setTimeout(() => item.classList.add('appear'), index * 30);
                    });
                }, 50);
            }, 150);
        }, 300); // 300ms防抖延迟
    });
    
    // 分类按钮点击事件 - 打开分类日程弹窗
    document.addEventListener('click', (e) => {
        // 处理新的分类按钮
        const categoryBtn = e.target.closest('.category-btn');
        if (categoryBtn) {
            const category = categoryBtn.dataset.category;
            if (category) {
                openCategoryScheduleModal(category);
                return;
            }
        }
        
        // 保留原有的分类标签点击处理
        const categoryTag = e.target.closest('.category-tag, .category-badge');
        if (categoryTag && !e.target.closest('.edit-btn')) {
            const categoryText = categoryTag.textContent.trim();
            // 处理数字后缀，例如"工作 (5)" -> "工作"
            const category = categoryText.split('(')[0].trim();
            openCategoryScheduleModal(category);
        }
    });
    
    // 分类弹窗关闭按钮
    if (categoryModalCloseBtn) {
        categoryModalCloseBtn.addEventListener('click', closeCategoryScheduleModal);
    }
    
    if (categoryScheduleModal) {
        categoryScheduleModal.addEventListener('click', (e) => {
            if (e.target === categoryScheduleModal) {
                closeCategoryScheduleModal();
            }
        });
    }
    
    // 分类弹窗过滤动画
    function applyCategoryFilterWithAnimation() {
        // 回到列表顶部
        if (categoryScheduleList) {
            categoryScheduleList.scrollTo({ top: 0, behavior: 'smooth' });
        }
        
        // 添加退出动画
        const existingItems = categoryScheduleList.querySelectorAll('.schedule-item');
        existingItems.forEach(item => item.classList.add('schedule-item-exit'));
        
        // 延迟后重新渲染
        setTimeout(() => {
            renderCategorySchedules();
            
            // 添加进入动画
            setTimeout(() => {
                const newItems = categoryScheduleList.querySelectorAll('.schedule-item:not(.schedule-item-exit)');
                newItems.forEach((item, index) => {
                    item.classList.add('schedule-item-enter');
                    setTimeout(() => item.classList.add('appear'), index * 30);
                });
            }, 50);
        }, 150);
    }
    
    // 分类弹窗状态过滤按钮
    if (categoryStatusButtons.all) {
        categoryStatusButtons.all.addEventListener('click', () => {
            categoryFilterState.status = 'all';
            updateCategoryStatusButtons('all');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryStatusButtons.pending) {
        categoryStatusButtons.pending.addEventListener('click', () => {
            categoryFilterState.status = 'pending';
            updateCategoryStatusButtons('pending');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryStatusButtons.completed) {
        categoryStatusButtons.completed.addEventListener('click', () => {
            categoryFilterState.status = 'completed';
            updateCategoryStatusButtons('completed');
            applyCategoryFilterWithAnimation();
        });
    }
    
    // 分类弹窗时间范围按钮
    if (categoryRangeButtons.today) {
        categoryRangeButtons.today.addEventListener('click', () => {
            categoryFilterState.timeRange = 'today';
            updateCategoryRangeButtons('today');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryRangeButtons.week) {
        categoryRangeButtons.week.addEventListener('click', () => {
            categoryFilterState.timeRange = 'week';
            updateCategoryRangeButtons('week');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryRangeButtons.month) {
        categoryRangeButtons.month.addEventListener('click', () => {
            categoryFilterState.timeRange = 'month';
            updateCategoryRangeButtons('month');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryRangeButtons.year) {
        categoryRangeButtons.year.addEventListener('click', () => {
            categoryFilterState.timeRange = 'year';
            updateCategoryRangeButtons('year');
            applyCategoryFilterWithAnimation();
        });
    }
    
    if (categoryRangeButtons.all) {
        categoryRangeButtons.all.addEventListener('click', () => {
            categoryFilterState.timeRange = 'all';
            updateCategoryRangeButtons('all');
            applyCategoryFilterWithAnimation();
        });
    }
    
    // 分类弹窗搜索框（带防抖）
    if (categorySearchInput) {
        let searchTimeout;
        categorySearchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            categoryFilterState.searchTerm = e.target.value;
            
            searchTimeout = setTimeout(() => {
                // 回到列表顶部
                if (categoryScheduleList) {
                    categoryScheduleList.scrollTo({ top: 0, behavior: 'smooth' });
                }
                
                // 添加退出动画
                const existingItems = categoryScheduleList.querySelectorAll('.schedule-item');
                existingItems.forEach(item => item.classList.add('schedule-item-exit'));
                
                // 延迟后重新渲染
                setTimeout(() => {
                    renderCategorySchedules();
                    
                    // 添加进入动画
                    setTimeout(() => {
                        const newItems = categoryScheduleList.querySelectorAll('.schedule-item:not(.schedule-item-exit)');
                        newItems.forEach((item, index) => {
                            item.classList.add('schedule-item-enter');
                            setTimeout(() => item.classList.add('appear'), index * 30);
                        });
                    }, 50);
                }, 150);
            }, 300); // 300ms防抖延迟
        });
    }
    
    // ESC键关闭分类弹窗
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && categoryScheduleModal && categoryScheduleModal.style.display === 'flex') {
            closeCategoryScheduleModal();
        }
    });
}

// 日历组件
let currentDate = new Date();

// 初始化日历
async function initCalendar() {
    currentDate = new Date();
    initYearMonthSelectors();
    await renderCalendar();
    
    // 移除旧事件监听器避免重复添加
    const prevMonthBtn = document.getElementById('prev-month');
    const nextMonthBtn = document.getElementById('next-month');
    const backToCurrentMonthBtn = document.getElementById('back-to-current-month');
    
    if (prevMonthBtn._prevHandler) prevMonthBtn.removeEventListener('click', prevMonthBtn._prevHandler);
    if (nextMonthBtn._nextHandler) nextMonthBtn.removeEventListener('click', nextMonthBtn._nextHandler);
    if (backToCurrentMonthBtn._backHandler) backToCurrentMonthBtn.removeEventListener('click', backToCurrentMonthBtn._backHandler);
    
    // 添加月份切换按钮事件
    prevMonthBtn._prevHandler = async () => {
        currentDate.setMonth(currentDate.getMonth() - 1);
        await renderCalendar();
    };
    prevMonthBtn.addEventListener('click', prevMonthBtn._prevHandler);
    
    nextMonthBtn._nextHandler = async () => {
        currentDate.setMonth(currentDate.getMonth() + 1);
        await renderCalendar();
    };
    nextMonthBtn.addEventListener('click', nextMonthBtn._nextHandler);
    
    // 添加回到本月按钮事件
    backToCurrentMonthBtn._backHandler = async () => {
        const now = new Date();
        currentDate = new Date(now.getFullYear(), now.getMonth(), 1);
        await renderCalendar();
    };
    backToCurrentMonthBtn.addEventListener('click', backToCurrentMonthBtn._backHandler);
}

// 初始化年份和月份选择器
function initYearMonthSelectors() {
    const yearSelector = document.getElementById('year-selector');
    const yearDropdown = document.getElementById('year-dropdown');
    const monthSelector = document.getElementById('month-selector');
    const monthDropdown = document.getElementById('month-dropdown');
    
    // 清空下拉菜单
    yearDropdown.innerHTML = '';
    monthDropdown.innerHTML = '';
    
    // 生成年份选项（当前年份前后10年）
    const currentYear = new Date().getFullYear();
    for (let i = currentYear - 10; i <= currentYear + 10; i++) {
        const yearOption = document.createElement('div');
        yearOption.className = 'px-3 py-2 hover:bg-gray-100 cursor-pointer text-center';
        yearOption.textContent = i;
        yearOption.addEventListener('click', async () => {
            currentDate.setFullYear(i);
            await renderCalendar();
            yearDropdown.classList.add('hidden');
        });
        yearDropdown.appendChild(yearOption);
    }
    
    // 生成月份选项
    const monthNames = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
    for (let i = 0; i < 12; i++) {
        const monthOption = document.createElement('div');
        monthOption.className = 'px-3 py-2 hover:bg-gray-100 cursor-pointer text-center';
        monthOption.textContent = monthNames[i];
        monthOption.addEventListener('click', async () => {
            currentDate.setMonth(i);
            await renderCalendar();
            monthDropdown.classList.add('hidden');
        });
        monthDropdown.appendChild(monthOption);
    }
    
    // 移除旧事件监听器
    if (yearSelector._clickHandler) yearSelector.removeEventListener('click', yearSelector._clickHandler);
    if (monthSelector._clickHandler) monthSelector.removeEventListener('click', monthSelector._clickHandler);
    if (yearDropdown._clickHandler) yearDropdown.removeEventListener('click', yearDropdown._clickHandler);
    if (monthDropdown._clickHandler) monthDropdown.removeEventListener('click', monthDropdown._clickHandler);
    if (document._calendarClickHandler) document.removeEventListener('click', document._calendarClickHandler);
    
    // 年份选择器点击事件
    yearSelector._clickHandler = (e) => {
        e.stopPropagation();
        yearDropdown.classList.toggle('hidden');
        monthDropdown.classList.add('hidden');
    };
    yearSelector.addEventListener('click', yearSelector._clickHandler);
    
    // 月份选择器点击事件
    monthSelector._clickHandler = (e) => {
        e.stopPropagation();
        monthDropdown.classList.toggle('hidden');
        yearDropdown.classList.add('hidden');
    };
    monthSelector.addEventListener('click', monthSelector._clickHandler);
    
    // 点击其他地方关闭下拉菜单
    document._calendarClickHandler = () => {
        yearDropdown.classList.add('hidden');
        monthDropdown.classList.add('hidden');
    };
    document.addEventListener('click', document._calendarClickHandler);
    
    // 阻止下拉菜单内部事件冒泡
    yearDropdown._clickHandler = (e) => e.stopPropagation();
    yearDropdown.addEventListener('click', yearDropdown._clickHandler);
    
    monthDropdown._clickHandler = (e) => e.stopPropagation();
    monthDropdown.addEventListener('click', monthDropdown._clickHandler);
}

// 渲染日历
async function renderCalendar() {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    
    // 更新显示
    const currentYearSpan = document.getElementById('current-year');
    const currentMonthSpan = document.getElementById('current-month');
    if (currentYearSpan && currentMonthSpan) {
        currentYearSpan.textContent = `${year}`;
        currentMonthSpan.textContent = `${month + 1}`;
    }
    
    // 控制回到本月按钮显示
    const backToCurrentMonthBtn = document.getElementById('back-to-current-month');
    const now = new Date();
    if (year !== now.getFullYear() || month !== now.getMonth()) {
        backToCurrentMonthBtn.classList.remove('opacity-0', 'translate-y-2', 'pointer-events-none');
        backToCurrentMonthBtn.classList.add('opacity-100', 'translate-y-0', 'pointer-events-auto');
    } else {
        backToCurrentMonthBtn.classList.remove('opacity-100', 'translate-y-0', 'pointer-events-auto');
        backToCurrentMonthBtn.classList.add('opacity-0', 'translate-y-2', 'pointer-events-none');
    }
    
    const calendarBody = document.getElementById('calendar-body');
    
    // 淡出动画
    calendarBody.classList.add('calendar-fade-out');
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 创建文档片段避免频繁DOM操作
    const fragment = document.createDocumentFragment();
    const schedules = await getSchedulesFromStorage();
    
    // 计算日历数据
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const firstDayIndex = firstDay.getDay();
    const daysInMonth = lastDay.getDate();
    const prevLastDay = new Date(year, month, 0).getDate();
    
    // 创建日历格子
    let date = 1;
    let prevDate = prevLastDay - firstDayIndex + 1;
    let nextDate = 1;
    
    // 最多6行日历
    for (let i = 0; i < 6; i++) {
        const row = document.createElement('tr');
        
        for (let j = 0; j < 7; j++) {
            const cell = document.createElement('td');
            cell.classList.add('border', 'border-gray-200', 'p-1', 'calendar-cell');
            
            const cellContent = document.createElement('div');
            cellContent.classList.add('min-h-[100px]', 'p-2', 'relative');
            
            // 日期渲染
            if (i === 0 && j < firstDayIndex) {
                // 上个月日期
                cellContent.innerHTML = `<div class="text-gray-400 text-sm mb-1">${prevDate}</div>`;
                prevDate++;
                cell.classList.add('bg-gray-50', 'cursor-not-allowed');
                cell.style.cursor = 'default';
            } else if (date > daysInMonth) {
                // 下个月日期
                cellContent.innerHTML = `<div class="text-gray-400 text-sm mb-1">${nextDate}</div>`;
                nextDate++;
                cell.classList.add('bg-gray-50', 'cursor-not-allowed');
                cell.style.cursor = 'default';
            } else {
                // 当月日期
                const currentDateString = `${year}-${String(month + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`;
                
                // 高亮今天
                const today = new Date();
                const isToday = today.getFullYear() === year && today.getMonth() === month && today.getDate() === date;
                
                if (isToday) {
                    cell.classList.add('bg-primary/10');
                    cellContent.innerHTML = `<div class="text-primary font-bold text-sm mb-1">${date}</div>`;
                } else {
                    cellContent.innerHTML = `<div class="text-sm mb-1">${date}</div>`;
                }
                
                // 显示日程
                const daySchedules = schedules.filter(schedule => schedule.date === currentDateString);
                if (daySchedules.length > 0) {
                    const scheduleList = document.createElement('div');
                    scheduleList.classList.add('space-y-1', 'mt-1');
                    
                    daySchedules.forEach(schedule => {
                        const scheduleItem = document.createElement('div');
                        scheduleItem.classList.add('text-xs', 'truncate', 'p-1', 'rounded', 'schedule-item-hover');
                        
                        // 分类颜色
                        let bgColor = '';
                        switch(schedule.category) {
                            case '工作': bgColor = 'bg-primary'; break;
                            case '学习': bgColor = 'bg-secondary'; break;
                            case '生活': bgColor = 'bg-red-500'; break;
                            case '健康': bgColor = 'bg-success'; break;
                            default: bgColor = 'bg-gray-400';
                        }
                        
                        scheduleItem.classList.add(bgColor, 'text-white');
                        
                        // 完成状态
                        if (schedule.isCompleted) {
                            scheduleItem.innerHTML = `<i class="fa fa-check mr-1"></i>${schedule.title}`;
                        } else {
                            scheduleItem.textContent = schedule.title;
                        }
                        
                        // 编辑日程
                        scheduleItem.addEventListener('click', () => editSchedule(schedule.id));
                        scheduleList.appendChild(scheduleItem);
                    });
                    
                    cellContent.appendChild(scheduleList);
                }
                
                // 点击显示当日日程
                cell.addEventListener('click', () => {
                    if (!event.target.closest('.schedule-item-hover')) {
                        openDayScheduleModal(currentDateString);
                    }
                });
                
                // 双击快速添加日程
                cell.addEventListener('dblclick', (e) => {
                    e.stopPropagation();
                    const scheduleDate = document.getElementById('schedule-date');
                    scheduleDate.value = currentDateString;
                    openModal();
                });
                
                date++;
            }
            
            // 鼠标离开时滚动到顶部
            cellContent.addEventListener('mouseleave', function() { this.scrollTop = 0; });
            cell.appendChild(cellContent);
            row.appendChild(cell);
        }
        
        fragment.appendChild(row);
        
        // 所有日期添加完成，跳出循环
        if (date > daysInMonth && nextDate > 7) break;
    }
    
    // 双缓冲DOM替换
    calendarBody.innerHTML = '';
    calendarBody.appendChild(fragment);
    
    // 淡入动画
    calendarBody.classList.remove('calendar-fade-out');
    calendarBody.classList.add('calendar-fade-in');
    setTimeout(() => calendarBody.classList.remove('calendar-fade-in'), 300);
}


// 打开日期日程模态框
function openDayScheduleModal(dateString) {
    const modal = document.getElementById('day-schedule-modal');
    const modalTitle = document.getElementById('day-schedule-modal-title');
    const scheduleList = document.getElementById('day-schedule-list');
    
    if (!modal || !modalTitle || !scheduleList) return;
    
    // 格式化日期显示
    const date = new Date(dateString);
    const formattedDate = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
    modalTitle.textContent = `${formattedDate} 日程`;
    
    // 清空列表
    scheduleList.innerHTML = '';
    
    // 查找当天的日程
    const daySchedules = window.schedules.filter(schedule => schedule.date === dateString);
    
    if (daySchedules.length === 0) {
        // 如果没有日程，显示提示信息
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'text-center py-8 text-gray-500';
        emptyMessage.innerHTML = `<p>该日期暂无日程</p>`;
        scheduleList.appendChild(emptyMessage);
    } else {
        // 按时间排序日程
        const sortedSchedules = [...daySchedules].sort((a, b) => {
            const timeA = a.time || '00:00';
            const timeB = b.time || '00:00';
            return timeA.localeCompare(timeB);
        });
        
        // 创建日程列表项
        sortedSchedules.forEach(schedule => {
            const scheduleItem = document.createElement('div');
            scheduleItem.className = 'p-4 border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors';
            
            // 根据分类设置颜色
            let categoryClass = 'category-other';
            switch(schedule.category) {
                case '工作':
                    categoryClass = 'category-work';
                    break;
                case '学习':
                    categoryClass = 'category-study';
                    break;
                case '生活':
                    categoryClass = 'category-life';
                    break;
                case '健康':
                    categoryClass = 'category-health';
                    break;
            }
            
            // 构建日程项内容
            scheduleItem.innerHTML = `
                <div class="flex justify-between items-start mb-2">
                    <div class="flex items-center space-x-2">
                        <span class="category-tag ${categoryClass}">${schedule.category}</span>
                        ${schedule.reminder ? '<i class="fa fa-bell text-warning"></i>' : ''}
                    </div>
                    <span class="text-sm text-gray-500">${schedule.time || '全天'}</span>
                </div>
                <h4 class="font-medium text-gray-800 mb-1">${schedule.title}</h4>
                ${schedule.description ? `<p class="text-sm text-gray-600 mb-3">${schedule.description}</p>` : ''}
                <div class="flex justify-end space-x-2">
                    <button class="text-gray-500 hover:text-primary transition-colors edit-day-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-pencil"></i>
                    </button>
                    ${schedule.isCompleted ? `
                    <button class="text-gray-500 hover:text-warning transition-colors undo-day-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-undo"></i>
                    </button>` : `
                    <button class="text-gray-500 hover:text-success transition-colors complete-day-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-check"></i>
                    </button>`}
                    <button class="text-gray-500 hover:text-danger transition-colors delete-day-schedule-btn" data-id="${schedule.id}">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            `;
            
            scheduleList.appendChild(scheduleItem);
        });
        
        // 添加事件监听器
        document.querySelectorAll('.edit-day-schedule-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = e.currentTarget.dataset.id;
                closeDayScheduleModal();
                editSchedule(id);
            });
        });
        
        document.querySelectorAll('.complete-day-schedule-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = e.currentTarget.dataset.id;
                toggleCompleteSchedule(id, 'complete').then(() => {
                    openDayScheduleModal(dateString); // 刷新列表
                });
            });
        });
        
        document.querySelectorAll('.undo-day-schedule-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = e.currentTarget.dataset.id;
                toggleCompleteSchedule(id, 'undo').then(() => {
                    openDayScheduleModal(dateString); // 刷新列表
                });
            });
        });
        
        document.querySelectorAll('.delete-day-schedule-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = e.currentTarget.dataset.id;
                deleteSchedule(id).then(() => {
                    openDayScheduleModal(dateString); // 刷新列表
                    renderCalendar(); // 刷新日历
                });
            });
        });
    }
    
    // 显示模态框
    modal.classList.remove('hidden');
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // 存储当前日期用于添加日程
    modal.dataset.date = dateString;
}

// 关闭日期日程模态框
function closeDayScheduleModal() {
    const modal = document.getElementById('day-schedule-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
        document.body.style.overflow = '';
        // 清除存储的日期
        delete modal.dataset.date;
    }
}

// 添加日期日程模态框相关的事件监听器
function addDayScheduleModalListeners() {
    // 关闭按钮
    document.getElementById('close-day-schedule-modal-btn')?.addEventListener('click', closeDayScheduleModal);
    document.getElementById('close-day-schedule-btn')?.addEventListener('click', closeDayScheduleModal);
    
    // 添加日程按钮
    document.getElementById('add-day-schedule-btn')?.addEventListener('click', () => {
        const modal = document.getElementById('day-schedule-modal');
        const dateString = modal?.dataset.date;
        if (dateString) {
            closeDayScheduleModal();
            const scheduleDate = document.getElementById('schedule-date');
            if (scheduleDate) {
                scheduleDate.value = dateString;
                // 传入skipDateReset参数为true，避免openModal函数重置日期
                openModal('add', null, true);
            }
        }
    });
    
    // 点击模态框外部关闭
    document.getElementById('day-schedule-modal')?.addEventListener('click', (e) => {
        if (e.target === e.currentTarget) {
            closeDayScheduleModal();
        }
    });
}

// 应用启动
window.addEventListener('DOMContentLoaded', async () => {
    try {
        // 修复可能损坏的全局变量
        if (!Array.isArray(window.schedules)) window.schedules = [];
        
        // 加载数据
        window.schedules = await getSchedulesFromStorage();
        
        // 确保数据有效
        if (!Array.isArray(window.schedules)) {
            window.schedules = [];
            console.warn('修复了无效的schedules全局变量');
        }
        
        // 初始化
        addEventListeners();
        addDayScheduleModalListeners();
        await initApp();
        await initCalendar();
        
        // 数据导入导出
        document.getElementById('export-data-btn')?.addEventListener('click', exportUserData);
        document.getElementById('import-data-btn')?.addEventListener('click', importUserData);
        
        console.log('应用启动成功，共加载', window.schedules.length, '个日程');
    } catch (error) {
        console.error('应用启动失败:', error);
        
        // 故障恢复
        window.schedules = [];
        
        const mainContent = document.querySelector('main');
        if (mainContent) {
            mainContent.innerHTML = `
                <div class="text-center py-16">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">应用启动遇到问题</h2>
                    <p class="text-gray-600 mb-8">请尝试重新启动应用程序</p>
                    <button onclick="window.location.reload()" class="bg-primary text-white py-2 px-6 rounded-lg hover:bg-primary/90">
                        重新加载
                    </button>
                </div>
            `;
        }
    }
});
